package cn.com.nes.site.module.dao.inventory;

import cn.com.nes.common.util.DBUtils;
import cn.com.nes.common.util.Page;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionStatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
public class PurchaseDaoImpl extends BaseDaoImpl {
    private TransactionStatus newg_status = null;

    public PageData generatePurchaseId(DataReq req) {
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("生成订单编号失败");
        try {
            String orderId = DBUtils.getDjbh(req.getUinfo().getCompanyId(), "PDD");
            res.setKey(orderId);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    //获取最新订单ID的序号
    public Integer getPurchaseNewSerial(String purchaseId) {
        StringBuffer sb = new StringBuffer();
        sb.append("select serial from g_purchase where isNew='1' and  purchaseId='" + purchaseId + "' order by serial desc limit 1 ");
        List<Map<String, Object>> serial = this.getJdbcTemplate_newg().queryForList(sb.toString());
        if (serial.size() > 0) {
            return (Integer) serial.get(0).get("serial");
        } else {
            return null;
        }

    }

    public PageData getPurchaseList(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取订单登记列表失败");
        try {
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer();
            sb.append(" select a.uuid, a.purchaseId,a.purchaseName,  a.purchaseState,b.name purchaseStateName, a.applyUid,e.nickName applyName,DATE_FORMAT(a.applyTime,'%Y-%m-%d %H:%i:%s')  applyTime, a.customerID, n.companyName customerName  ");
            sb.append(" from g_purchase a ");
            sb.append(" INNER JOIN  t_param b on b.param_type='107' and   a.purchaseState=b.value ");
            sb.append(" INNER JOIN  t_company c on c.companyId=a.companyId ");
            sb.append(" left JOIN  t_department d on d.departmentId=a.departmentId ");
            sb.append(" left JOIN t_user e on e.id=a.applyUid ");
            sb.append(" left JOIN  t_company n on n.companyId=a.customerID ");

            sb.append("   WHERE a.isdelete='0' AND a.isNew='1' and serial=1  and  a.companyId='").append(req.getUinfo().getCompanyId()).append("'  ");
            //sb.append("    AND purchaseState in('01','02','03','04')  ");
//            if(!StringUtils.isEmpty((String) param.get("stateType")) &&"01".equals(param.get("stateType"))){
//            	sb.append("    AND purchaseState in('01','02','03','04')  ");
//            }
            if (!StringUtils.isEmpty((String) param.get("stateType")) && "02".equals(param.get("stateType"))) {
                sb.append("    AND purchaseState <>'01'  ");
            }

            //厂家名称
            if (!StringUtils.isEmpty((String) param.get("customerName"))) {
                sb.append(" and n.companyName like '%").append(param.get("customerName")).append("%' ");
            }
            //登记状态
            if (!StringUtils.isEmpty((String) param.get("purchaseState"))) {
                sb.append(" and a.purchaseState ='").append(param.get("purchaseState")).append("' ");
            }
            //订单开始时间
            if (!StringUtils.isEmpty((String) param.get("applyTimeBegin"))) {
                sb.append(" and a.applyTime >= '").append(param.get("applyTimeBegin")).append("' ");
            }
            //订单结束时间
            if (!StringUtils.isEmpty((String) param.get("applyTimeEnd"))) {
                sb.append(" and a.applyTime<'").append(param.get("applyTimeEnd")).append("' ");
            }
            sb.append("  order by a.createTime desc ");
            sb = DBUtils.sql_check(sb);
            sbfrom.append(sb.toString());
            int idx = sbfrom.indexOf(" from ");
            sbfrom.delete(0, idx);
            Page page = new Page(this.getJdbcTemplate_newg(), sbfrom.toString(), req.getPageid(), req.getPagesize(), res, new Object[]{});
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize());
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{});
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    //获取明细
    @SuppressWarnings({"unchecked", "rawtypes"})
    public PageData getPurchaseDetail(DataReq req) {
        Map<String, Object> param = req.getReqData();
        Map<String, Object> extData = new HashMap();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取订单详情失败");
        try {

            StringBuffer sb = new StringBuffer();
            sb.append(" select a.uuid, a.purchaseId,purchaseName, a.serial, a.purchaseState,b.name purchaseStateName,a.companyId,c.companyName, a.departmentId,d.departmentName, a.applyUid,e.nickName applyName, DATE_FORMAT(a.applyTime,'%Y-%m-%d %H:%i:%s')  applyTime, a.customerID, n.companyName customerName, a.address, a.phone, a.cusname, a.reviewerId,h.nickName reviewerName , DATE_FORMAT(a.reviewerTime,'%Y-%m-%d %H:%i:%s')  reviewerTime , a.reviewerResult,i.`name` reviewerResultName , a.reviewerSuggest, a.isNew, a.createUid, a.createTime, a.modifyUid, a.modifyTime, a.isdelete,a.companyMemo ");
            sb.append(" FROM g_purchase a ");
            sb.append(" INNER JOIN  t_param b on b.param_type='107' and   a.purchaseState=b.value ");
            sb.append(" INNER JOIN  t_company c on c.companyId=a.companyId ");
            sb.append(" left JOIN  t_department d on d.departmentId=a.departmentId ");
            sb.append(" left JOIN t_user e on e.id=a.applyUid ");
            sb.append(" left JOIN t_user h on h.id=a.reviewerId ");
            sb.append(" left JOIN  t_param i on i.param_type='100' and   i.`value`=a.reviewerResult ");
            sb.append(" left JOIN  t_company n on n.companyId=a.customerID ");
            sb.append("   WHERE a.isdelete='0' AND a.isNew='1' and serial=1  and a.purchaseId=?  ");
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId")});

            List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();
            //获取商品列表
            if (list != null && list.size() > 0) {
                String companyId = req.getUinfo().getCompanyId();
                sb.delete(0, sb.length());
                sb.append("select a.uuid,a.purchaseId,b.goodsType,d.goodsTypeName,a.goodsUUid,b.goodsCode,"
                        + " b.goodsName,a.inoutNum,a.companyInoutNum,a.memo,b.brand,b.goodsModel,b.packingSize,b.unit"
                        + " from g_purchase a "
                        + " left join g_goods b on a.goodsUUid=b.uuid "
                        + " left join g_goodstype d on b.goodsType=d.goodsTypeId "
                        + " where a.isdelete='0' AND a.isNew='1' and  a.purchaseId=? "
                        + " and a.companyid=? and b.companyid=? and d.companyid=? "
                        + " order by a.serial asc ");
                List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId"), companyId, companyId, companyId});
                goodList = dto;
            }

            //获取入库信息
            if (list != null && list.size() > 0) {
                sb.delete(0, sb.length());
                sb.append("select a.applyId,a.goodsUUid,b.goodsCode,b.goodsName,a.orderType,b.goodsType,d.goodsTypeName,b.goodsModel,b.packingSize,b.unit,c.customerId,e.companyName customerName,c.applyTime,c.inoutNum,c.memo,sum(a.inoutNum) orderinNum,a.inoutNum currentNum,a.warehouseId,true flagshow\n" +
                        " from g_order_in a " +
                        " left join g_goods b on a.goodsUUid=b.uuid " +
                        " left join g_order_in_apply c on a.applyId=c.applyId and a.goodsUUid=c.goodsUUid " +
                        " left join g_goodstype d on b.goodsType=d.goodsTypeId and d.companyId = b.companyId and d.isdelete = 0 " +
                        " left join t_company e on c.customerID=e.companyId " +
                        " where a.isdelete=0 and c.purchaseId=? " +
                        " group by a.applyId,a.goodsUUid " +
                        " order by a.warehouseTime asc,a.serial asc ");
                List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId")});
                if(dto.size()>0){
                    Map<String, List<Map<String, Object>>> groupedByApplyId = dto.stream()
                            .collect(Collectors.groupingBy(map -> (String) map.get("applyId")));
                    List<Map<String, Object>> groupedResults = new ArrayList<>();
                    int index = 0;
                    for (Map.Entry<String, List<Map<String, Object>>> entry : groupedByApplyId.entrySet()) {
                        Map<String, Object> groupInfo = new HashMap<>();
                        groupInfo.put("GroupName", "第" + (index + 1) + "次入库");
                        groupInfo.put("GroupData", entry.getValue());
                        groupedResults.add(groupInfo);
                        index++;
                    }
                    extData.put("orderIn", groupedResults);
                }
            }

            extData.put("info", list.size() > 0 ? list.get(0) : null);
            extData.put("goods", goodList);
            res.setExtData(extData);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }


    @SuppressWarnings("unchecked")
    public PageData savePurchaseInfo(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("isdelete", "0");
        param.put("companyId", req.getUinfo().getCompanyId());
        param.put("applyUid", param.get("applyUid"));
        param.put("isNew", "1");
        JSONArray goodslist = (JSONArray) param.get("goodslist");
        try {
            param.put("purchaseState", "01");
            //goodslist不为空 新增
            if (goodslist.size() > 0) {
                for (int i = 0; i < goodslist.size(); i++) {
                    param.remove("uuid");
                    JSONObject object = (JSONObject) goodslist.get(i);
                    param.put("goodsUUid", object.get("goodsUUid"));
                    param.put("inoutNum", object.get("inoutNum"));
                    param.put("memo", object.get("memo"));
                    //设置序号
                    Integer serial = getPurchaseNewSerial((String) param.get("purchaseId"));
                    if (serial != null) {
                        param.put("serial", String.valueOf(serial + 1));
                    } else {
                        param.put("serial", "1");
                    }
                    PageData sqlInfo = getInsertSQL(req);
                    if (sqlInfo.getRetCode() != 0) {
                        rollback_newg(newg_status);
                        return sqlInfo;
                    }
                    final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
                    final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
                    this.getJdbcTemplate_newg().update(sb_field.toString(),
                            listData.toArray());
                }
            } else { //goodslist为空 修改
                param.remove("isdelete");
                param.put("keys", "purchaseId");
                PageData sqlInfo = getUpdateSQL(req);
                if (sqlInfo.getRetCode() != 0) {
                    rollback_newg(newg_status);
                    return sqlInfo;
                }
                final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
                final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
                this.getJdbcTemplate_newg().update(sb_field.toString(),
                        listData.toArray());
            }


            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();

        } finally {

        }
        return res;
    }

    //订单部分提交
    @SuppressWarnings("unchecked")
    public PageData updatePurchaseInfo(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        try {
            param.put("keys", "uuid");
            PageData sqlInfo = getUpdateSQL(req);
            if (sqlInfo.getRetCode() != 0) {
                rollback_newg(newg_status);
                return sqlInfo;
            }
            final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
            final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
            this.getJdbcTemplate_newg().update(sb_field.toString(),
                    listData.toArray());

            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();

        } finally {

        }
        return res;
    }

    //提交订单进行审核
    @SuppressWarnings("unchecked")
    public PageData applyReviewerPurchaseInfo(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("purchaseState", "02");
        param.put("isNew", "1");
        param.put("keys", "purchaseId;isNew");

        try {
            PageData sqlInfo = getUpdateSQL(req);
            if (sqlInfo.getRetCode() != 0) {
                rollback_newg(newg_status);
                return sqlInfo;
            }
            final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
            final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
            this.getJdbcTemplate_newg().update(sb_field.toString(),
                    listData.toArray());


            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
            res.setKey((String) param.get("uuid"));
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();

        } finally {

        }
        return res;
    }

    //删除订单
    @SuppressWarnings("unchecked")
    public PageData delPurchase(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("isdelete", "1");

        try {
            param.put("keys", "purchaseId");
            PageData sqlInfo = getUpdateSQL(req);
            if (sqlInfo.getRetCode() != 0) {
                rollback_newg(newg_status);
                return sqlInfo;
            }
            final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
            final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
            this.getJdbcTemplate_newg().update(sb_field.toString(),
                    listData.toArray());

            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    //删除订单商品
    @SuppressWarnings("unchecked")
    public PageData delPurchaseGoods(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("isdelete", "1");

        try {
            param.put("keys", "uuid");
            PageData sqlInfo = getUpdateSQL(req);
            if (sqlInfo.getRetCode() != 0) {
                rollback_newg(newg_status);
                return sqlInfo;
            }
            final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
            final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
            this.getJdbcTemplate_newg().update(sb_field.toString(),
                    listData.toArray());


            res.setRetCode(0);
            res.setRetMessage("OK");

            //如果删除的serial为1的话 把所有其他的serial减1
            StringBuffer sb = new StringBuffer();
            sb.append("select a.serial,a.purchaseId from g_purchase a where a.uuid='").append(param.get("uuid")).append("' ");
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString());
            Integer serial = (Integer) list.get(0).get("serial");
            String purchaseId = (String) list.get(0).get("purchaseId");
            if (serial == 1) {
                //更新serial-1
                sb.delete(0, sb.length());
                sb.append("update g_purchase set serial=serial-1 where purchaseId='").append(purchaseId).append("' ");
                int i = this.getJdbcTemplate_newg().update(sb.toString());
                if (i < 0) {
                    rollback_newg(newg_status);
                    res.setRetCode(9);
                    res.setRetMessage("删除失败!");
                    return res;
                }
            }
            commit_newg(newg_status);
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();

        } finally {

        }
        return res;
    }

    //保存供应商审核结果
    @SuppressWarnings("unchecked")
    public PageData savePurchaseReviewerInfo(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("keys", "purchaseId");
        if (!StringUtils.isEmpty((String) param.get("reviewerResult")) && "01".equals((String) param.get("reviewerResult"))) {
            param.put("purchaseState", "03");
        }
        if (!StringUtils.isEmpty((String) param.get("reviewerResult")) && "02".equals((String) param.get("reviewerResult"))) {
            param.put("purchaseState", "04");
        }
        try {
            PageData sqlInfo = getUpdateSQL(req);
            if (sqlInfo.getRetCode() != 0) {
                rollback_newg(newg_status);
                return sqlInfo;
            }
            final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
            final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
            this.getJdbcTemplate_newg().update(sb_field.toString(), listData.toArray());

            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
            res.setKey((String) param.get("purchaseId"));
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();

        } finally {

        }
        return res;
    }

    //---------厂家订单处理
    public PageData getCompanyPurchaseList(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取代理商订单列表失败");
        try {
            StringBuffer sb = new StringBuffer();
            StringBuffer sbfrom = new StringBuffer();
            sb.append(" select ifnull(a.companyInoutCount,0) companyInoutCount,a.uuid, a.purchaseId,a.purchaseName,  a.purchaseState,b.name purchaseStateName,a.companyId,c.companyName,DATE_FORMAT(a.reviewerTime,'%Y-%m-%d %H:%i:%s')  applyTime, a.applyUid,e.nickName applyName,a.companyMemo   ");
            sb.append(" from g_purchase a ");
            sb.append(" left JOIN  t_param b on b.param_type='107' and   a.purchaseState=b.value ");
            sb.append(" left JOIN  t_company c on c.companyId=a.companyId ");
            sb.append(" left JOIN t_user e on e.id=a.applyUid ");
            //改为自己处理自己的订单
            sb.append("   WHERE a.isdelete='0' AND a.isNew='1' and serial=1  and  a.companyId='").append(req.getUinfo().getCompanyId()).append("'  ");
            //sb.append("   WHERE a.isdelete='0' AND a.isNew='1' and serial=1  and  a.customerID='").append(req.getUinfo().getCompanyId()).append("'  ");
            sb.append("    AND purchaseState in('03','05','06')  ");

            //厂家名称
            if (!StringUtils.isEmpty((String) param.get("customerName"))) {
                sb.append(" and c.companyName like '%").append(param.get("customerName")).append("%' ");
            }
            //登记状态
            if (!StringUtils.isEmpty((String) param.get("purchaseState"))) {
                sb.append(" and a.purchaseState ='").append(param.get("purchaseState")).append("' ");
            }
            //订单开始时间
            if (!StringUtils.isEmpty((String) param.get("applyTimeBegin"))) {
                sb.append(" and a.reviewerTime >= '").append(param.get("applyTimeBegin")).append("' ");
            }
            //订单结束时间
            if (!StringUtils.isEmpty((String) param.get("applyTimeEnd"))) {
                sb.append(" and a.reviewerTime<'").append(param.get("applyTimeEnd")).append("' ");
            }
            sb.append("  order by a.reviewerTime desc ");
            sb = DBUtils.sql_check(sb);
            sbfrom.append(sb.toString());
            int idx = sbfrom.indexOf(" from ");
            sbfrom.delete(0, idx);
            Page page = new Page(this.getJdbcTemplate_newg(), sbfrom.toString(), req.getPageid(), req.getPagesize(), res, new Object[]{});
            sb.append(" limit ").append(page.getOffsetlimit()).append(",").append(req.getPagesize());
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{});
            res.setPage(list);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    //获取厂家订单处理明细
    public PageData getCompanyPurchaseDetail(DataReq req) {
        Map<String, Object> param = req.getReqData();
        Map<String, Object> extData = new HashMap();
        PageData res = new PageData();
        res.setRetCode(9);
        res.setRetMessage("获取订单详情失败");
        try {

            StringBuffer sb = new StringBuffer();
            sb.append(" select a.companyInoutCount,a.uuid, a.purchaseId,purchaseName, a.serial, a.purchaseState,b.name purchaseStateName,a.companyId,c.companyName,  a.applyUid,e.nickName applyName, DATE_FORMAT(a.reviewerTime,'%Y-%m-%d %H:%i:%s')  applyTime, a.customerID, n.companyName customerName,  a.companyDealUserId,j.nickName companyDealUserName, a.companyDealTime, a.companyResult,k.`name` companyResultName,a.companyMemo, a.isNew, a.createUid, a.createTime, a.modifyUid, a.modifyTime, a.isdelete,a.cusname,a.phone,a.address ");
            sb.append(" FROM g_purchase a ");
            sb.append(" left JOIN t_param b on b.param_type='107' and   a.purchaseState=b.value ");
            sb.append(" left JOIN t_company c on c.companyId=a.companyId ");
            sb.append(" left JOIN t_user e on e.id=a.applyUid ");
            sb.append(" left JOIN t_company n on n.companyId=a.customerID ");
            sb.append(" left JOIN t_user j on j.id=a.companyDealUserId ");
            sb.append(" left JOIN t_param k on k.param_type='109' and  k.value=a.companyResult ");
            sb.append(" WHERE a.isdelete='0' AND a.isNew='1' and serial=1  and a.purchaseId=?  ");
            List<Map<String, Object>> list = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId")});

            List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();
            //获取商品列表
            if (list != null && list.size() > 0) {
                String companyId = (String) list.get(0).get("companyId");
                sb.delete(0, sb.length());
                sb.append("select a.uuid,a.purchaseId,b.goodsType,d.goodsTypeName,a.goodsUUid,b.goodsCode,"
                        + " b.goodsName,b.sbmc,a.inoutNum,0 companyInoutNum,ifnull(a.companyInoutNum,0) companyInoutNumOld,ifnull(a.companyInoutCount,0) companyInoutCountOld,a.memo,b.brand,b.goodsModel,b.packingSize,b.unit"
                        + " from g_purchase a "
                        + " left join g_goods b on a.goodsUUid=b.uuid "
                        + " left join g_goodstype d on b.goodsType=d.goodsTypeId "
                        + " where a.isdelete='0' AND a.isNew='1' and  a.purchaseId=? "
                        + " and a.companyid=? and b.companyid=? and d.companyid=? "
                        + " order by a.serial asc ");
                List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId"), companyId, companyId, companyId});
                goodList = dto;
            }

            //获取入库信息
            if (list != null && list.size() > 0) {
                sb.delete(0, sb.length());
                sb.append("select a.applyId,a.goodsUUid,b.goodsCode,b.goodsName,a.orderType,b.goodsType,d.goodsTypeName,b.goodsModel,b.packingSize,b.unit,c.customerId,e.companyName customerName,c.applyTime,c.inoutNum,c.memo,sum(a.inoutNum) orderinNum,a.inoutNum currentNum,a.warehouseId,true flagshow\n" +
                        " from g_order_in a " +
                        " left join g_goods b on a.goodsUUid=b.uuid " +
                        " left join g_order_in_apply c on a.applyId=c.applyId and a.goodsUUid=c.goodsUUid " +
                        " left join g_goodstype d on b.goodsType=d.goodsTypeId and d.companyId = b.companyId and d.isdelete = 0 " +
                        " left join t_company e on c.customerID=e.companyId " +
                        " where a.isdelete=0 and c.purchaseId=? " +
                        " group by a.applyId,a.goodsUUid " +
                        " order by a.warehouseTime asc,a.serial asc ");
                List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString(), new Object[]{param.get("purchaseId")});
                if(dto.size()>0){
                    Map<String, List<Map<String, Object>>> groupedByApplyId = dto.stream()
                            .collect(Collectors.groupingBy(map -> (String) map.get("applyId")));
                    List<Map<String, Object>> groupedResults = new ArrayList<>();
                    int index = 0;
                    for (Map.Entry<String, List<Map<String, Object>>> entry : groupedByApplyId.entrySet()) {
                        Map<String, Object> groupInfo = new HashMap<>();
                        groupInfo.put("GroupName", "第" + (index + 1) + "次入库");
                        groupInfo.put("GroupData", entry.getValue());
                        groupedResults.add(groupInfo);
                        index++;
                    }
                    extData.put("orderIn", groupedResults);
                }
            }

            extData.put("info", list.size() > 0 ? list.get(0) : null);
            extData.put("goods", goodList);
            res.setExtData(extData);
            res.setRetCode(0);
            res.setRetMessage("OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    //厂家处理确认，保存供应商审核结果
    public PageData saveCompanyPurchaseDeal(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("keys", "uuid");
        param.put("	companyDealUserId", req.getUinfo().getId());
        //param.put("	companyDealTime",);
        JSONArray goodslist = (JSONArray) param.get("goodslist");
        if (!StringUtils.isEmpty((String) param.get("companyResult")) && "01".equals((String) param.get("companyResult"))) {
            param.put("purchaseState", "05");
        }
        if (!StringUtils.isEmpty((String) param.get("companyResult")) && "02".equals((String) param.get("companyResult"))) {
            param.put("purchaseState", "06");
        }
        if (!StringUtils.isEmpty((String) param.get("companyResult")) && "01".equals((String) param.get("companyResult"))) {
            //校验订单商品是否在厂家的商品列表中存在
            StringBuffer sb = new StringBuffer();
            sb.delete(0, sb.length());
            sb.append(" select GROUP_CONCAT(d.uuid) uuid from g_purchase a  ");
            sb.append(" INNER JOIN  g_goods d on d.uuid=a.goodsUUid and d.companyId=a.companyId   ");
            sb.append(" where purchaseId='").append((String) param.get("purchaseId")).append("' and not EXISTS(select 1 from g_goods e where e.companyId=a.customerID )  ");
            //sb.append(" where purchaseId='").append((String) param.get("purchaseId")).append("' and not EXISTS(select 1 from g_goods e where e.sbxh=d.sbxh and   e.companyId=a.customerID )  ");

            List<Map<String, Object>> dto = this.getJdbcTemplate_newg().queryForList(sb.toString());
            if (dto.size() > 0) {
                if (!StringUtils.isEmpty((String) dto.get(0).get("goodsName"))) {
                    rollback_newg(newg_status);
                    res.setRetCode(9);
                    res.setRetMessage("请检查订单商品是否在商品列表中,商品名：" + dto.get(0).get("goodsName"));
                    return res;
                }
            }
        }
        try {
            if (goodslist.size() > 0) {
                for (int i = 0; i < goodslist.size(); i++) {
                    JSONObject object = (JSONObject) goodslist.get(i);
                    param.put("uuid", object.get("uuid"));
                    param.put("goodsUUid", object.get("goodsUUid"));
                    param.put("inoutNum", object.get("inoutNum"));
                    param.put("memo", object.get("memo"));
                    param.put("companyInoutNum", object.get("companyInoutNum"));

                    PageData sqlInfo = getUpdateSQL(req);
                    if (sqlInfo.getRetCode() != 0) {
                        rollback_newg(newg_status);
                        return sqlInfo;
                    }
                    final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
                    final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
                    this.getJdbcTemplate_newg().update(sb_field.toString(),
                            listData.toArray());
                }
            }

            res.setRetCode(0);
            res.setRetMessage("OK");
            if (!StringUtils.isEmpty((String) param.get("companyResult")) && "01".equals((String) param.get("companyResult"))) {
                //更新厂家商品id
                StringBuffer sb = new StringBuffer();
                sb.delete(0, sb.length());
                sb.append(" UPDATE g_purchase a  ");
                sb.append(" INNER JOIN  g_goods d on d.uuid=a.goodsUUid and d.companyId=a.companyId   ");
                sb.append(" INNER JOIN g_goods e on e.sbxh=d.sbxh  and e.companyId=a.customerID  ");
                sb.append(" set  a.companyGoodsId=e.uuid   ");
                sb.append(" where purchaseId='").append((String) param.get("purchaseId")).append("'  ");

                int k = this.getJdbcTemplate_newg().update(sb.toString());
                if (k < 0) {
                    rollback_newg(newg_status);
                    res.setRetCode(9);
                    res.setRetMessage("更新申请单厂家商品失败!");
                    return res;
                }

                //自动生成厂商的出库申请单
                sb.delete(0, sb.length());
                String orderId = DBUtils.getDjbh(req.getUinfo().getCompanyId(), "SQD");
                sb.append(" INSERT INTO g_order_out_apply (	uuid,	applyId,	purchaseId,	serial,	orderType,	orderState,	companyId,	departmentId,	applyUid,	applyTime,	customerID,	customerName,	address,	phone,	cusname,	goodsUUid,	inoutNum,	memo,	isdelete) ");
                sb.append(" SELECT  UUID(),	'").append(orderId).append("' applyId,	a.purchaseId,	(@rownum:=@rownum + 1) as serial ,	'03' orderType,	'01' orderState,	a.customerID companyId,	'").append(req.getUinfo().getDepartmentId()).append("' departmentId,	'").append(req.getUinfo().getId()).append("' applyUid,	now() applyTime,	a.companyId customerID,	b.companyName customerName,	b.address address, ");
                sb.append(" c.phone phone,	c.nickName cusname,a.companyGoodsId goodsUUid,	sum(a.companyInoutNum) inoutNum,	'',	'0' isdelete  ");
                sb.append(" from g_purchase a ,t_company b,t_user c,(SELECT @rownum := 0) d");
                sb.append(" where b.companyId=a.companyId and c.id=a.applyUid  and  a.purchaseId='").append((String) param.get("purchaseId")).append("' ");
                sb.append(" group by a.purchaseId,a.companyGoodsId ORDER BY serial ");
                int j = this.getJdbcTemplate_newg().update(sb.toString());
                if (j < 0) {
                    rollback_newg(newg_status);
                    res.setRetCode(9);
                    res.setRetMessage("自动生成厂商出库申请单失败!");
                    return res;
                }
            }
            commit_newg(newg_status);
            res.setKey((String) param.get("purchaseId"));
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();
        } finally {

        }
        return res;
    }

    public PageData updatePurchaseState(DataReq req) {
        Map<String, Object> param = req.getReqData();
        PageData res = new PageData();
        newg_status = begin_newg();// 开启事物
        param.put("tableName", "g_purchase");
        param.put("keys", "uuid");
        param.put("companyDealUserId", req.getUinfo().getId());
        try {
            if (!StringUtils.isEmpty((String) param.get("companyResult")) && "01".equals((String) param.get("companyResult"))) {
                param.put("purchaseState", "05");
            }
            if (!StringUtils.isEmpty((String) param.get("companyResult")) && "02".equals((String) param.get("companyResult"))) {
                param.put("purchaseState", "06");
            }
            JSONArray goodslist = (JSONArray) param.get("goodslist");
            if (goodslist.size() > 0) {
                for (int i = 0; i < goodslist.size(); i++) {
                    JSONObject object = (JSONObject) goodslist.get(i);
                    param.put("uuid", object.get("uuid"));
                    param.put("goodsUUid", object.get("goodsUUid"));
                    param.put("inoutNum", object.get("inoutNum"));
                    param.put("memo", object.get("memo"));
                    if (!StringUtils.isEmpty((String) param.get("companyResult")) && "01".equals((String) param.get("companyResult"))) {
                        param.put("companyInoutNum", 1*(Integer.valueOf(object.get("companyInoutNumOld").toString()) + 1*(Integer.valueOf(object.get("companyInoutNum").toString()))));
                        param.put("companyInoutCount", 1*(Integer.valueOf(object.get("companyInoutCountOld").toString()) + 1));
                    }
                    PageData sqlInfo = getUpdateSQL(req);
                    if (sqlInfo.getRetCode() != 0) {
                        rollback_newg(newg_status);
                        return sqlInfo;
                    }
                    final StringBuffer sb_field = (StringBuffer) sqlInfo.getData().get("sb_field");
                    final List<String> listData = (List<String>) sqlInfo.getData().get("listData");
                    this.getJdbcTemplate_newg().update(sb_field.toString(),listData.toArray());
                }
            }
            commit_newg(newg_status);
            res.setRetCode(0);
            res.setRetMessage("OK");
            res.setKey((String) param.get("purchaseId"));
        } catch (Exception e) {
            rollback_newg(newg_status);
            e.printStackTrace();
        } finally {

        }
        return res;
    }

}
